package org.bulldog.playlist.message;

import org.bulldog.playlist.PlayListener;
import org.bulldog.playlist.notice.NoticePlayList;
import org.bulldog.playlist.program.ProgramPlayList;
import org.bulldog.playlist.util.ThreadUtil;

/**
 * Created by zhanghongbin on 2017/9/18.
 * 点播
 *
 * @author zhanghongbin
 * @version 1.0
 */
public final class MessagePlayList {

    //重置标识-(如再次点播)
    private static boolean resetFlag = true;

    private MessagePlayList() {

    }

    public static final void run(Message message, PlayListener playListener) {
        if (message.getCode() == Message.Code.EXIT) {
            synchronized (MessagePlayList.class) {
                resetFlag = true;
                MessagePlayList.class.notifyAll();
            }
        } else {
            synchronized (MessagePlayList.class) {
                resetFlag = false;
                ProgramPlayList.pause();
                NoticePlayList.pause();
                MessagePlayList.class.notifyAll();
            }
            _run(message, playListener);
        }
    }

    private static final void _run(final Message message, final PlayListener playListener) {
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    playListener.onPlay(PlayListener.Type.MESSAGE, message);
                    //当点播节目如果存在通知则需要播放通知
                    if (message.getCode() == Message.Code.PROGRAM) {
                        NoticePlayList.backroll();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        synchronized (MessagePlayList.class) {
            resetFlag = true;
            try {
                MessagePlayList.class.wait(message.getPlayDuration() * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (resetFlag) {
            ProgramPlayList.recover(playListener);
        }
    }
}
